/*
 * @Description: 项目入口文件
 * @Author: Haor
 * @Date: 2022-04-03 00:33:03
 * @LastEditTime: 2022-05-12 23:12:38
 * @LastEditors: Haor
 */

import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'
import { ValidationPipe } from './common/pipes/validation.pipe'
import * as express from 'express'
import { logger } from '@middlewares/logger.middleware'
import { TransformInterceptor } from '@interceptors/transform.interceptor'
import { HttpExceptionFilter } from '@filters/http.exception.filter'
import { AuthExceptionFilter } from '@filters/auth-exception.filter'
import { BusinessExceptionFilter } from '@filters/business-exception.filter'
import { SignExceptionFilter } from '@filters/sign-exception.filter'
import { ParamsExceptionFilter } from "@filters/params-exception.filter";
import { ServerExceptionFilter } from "@filters/server-exception.filter";
import { ConfigService } from "@config/config.service";

async function bootstrap() {
    const NODE_ENV: string = process.env.NODE_ENV
    const configService = new ConfigService(NODE_ENV)
	const app = await NestFactory.create(AppModule)
	app.useGlobalPipes(new ValidationPipe()) // 管道-全局拦截器拦截出参
	app.use(express.json()) // For parsing application/json
	app.use(express.urlencoded({ extended: true })) // For parsing application/x-www-form-urlencoded
	app.use(logger) // 中间件-监听所有的请求路由，并打印日志
	app.useGlobalInterceptors(new TransformInterceptor()) // 拦截器-全局拦截器拦截出参
	app.useGlobalFilters(new HttpExceptionFilter()) // 过滤器-全局异常过滤器
	app.useGlobalFilters(new AuthExceptionFilter()) // 过滤器-全局认证失败异常
	app.useGlobalFilters(new BusinessExceptionFilter()) // 过滤器-全局业务异常
    app.useGlobalFilters(new ParamsExceptionFilter()) // 过滤器-全局参数错误异常
	app.useGlobalFilters(new SignExceptionFilter()) // 过滤器-全局签名异常
	app.useGlobalFilters(new ServerExceptionFilter()) // 过滤器-服务异常
	app.setGlobalPrefix(configService['API_ROUTER_PREFIX']) // 设置API前缀，http://localhost:5001/test  =>  http://localhost:5001/v1/test
	app.enableCors() // 允许跨域
	await app.listen(configService['PORT'], () => {
	    console.log(`NODE_ENV=${NODE_ENV}`)
	    console.log(`NestAuth application running：http://localhost:${configService['PORT']}${configService['API_ROUTER_PREFIX']}`)
    })
}
bootstrap()
